//
//  YHTabBar.swift
//  YHWeibo
//
//  Created by yuhao.mac on 16/6/25.
//  Copyright © 2016年 yuhao.mac. All rights reserved.
//

import UIKit

//声明协议
protocol YHTabBarDelegate:NSObjectProtocol{
    //声明协议方法
    func composeButtonClick()
}

class YHTabBar: UITabBar {

    //声明代理
    weak var yhDelegate:YHTabBarDelegate?
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        let width = SCREENW / 5
        
        //记录标示
        var index: CGFloat = 0
        
        //通过遍历得到该类身上的子控件
        for value in self.subviews{
        
            if value.isKindOfClass(NSClassFromString("UITabBarButton")!){
                value.frame.size.width = width
                value.frame.origin.x = index * width
                
                index++
                
                if index == 2{
                    index++
                }
            }
        }
        
        //设置撰写按钮的frame
        composeButton.center.x = self.frame.width * 0.5
        composeButton.center.y = self.frame.height * 0.5
    }
    
    func setupUI(){
        addSubview(composeButton)
    }
    
    //撰写按钮
    private lazy var composeButton: UIButton = {
        let button = UIButton()
        //添加事件
        button.addTarget(self, action: "buttonClick", forControlEvents: .TouchUpInside)
        //设置背景图片
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: .Highlighted)
        button.setBackgroundImage(UIImage(named:"tabbar_compose_button"), forState: .Normal)
        
        //设置图片
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: .Highlighted)
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: .Normal)
        button.sizeToFit()
        
        return button
    }()
    
    //监听方法，如果是私有，必须加上@objc，防止系统找不到
    @objc private func buttonClick(){
        yhDelegate?.composeButtonClick()
    }

}
